<template>
  <div class="container">
    <!-- 导航栏 -->
    <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="onClickLeft" />

    <!-- 商品列表 -->

    <van-swipe-cell v-if="cartList.length" v-for="item in cartList" :key="item.id" class="goods-card">
      <van-row :data="cartList" justify="center" align="center">
        <!-- 复选框 -->
        <van-col>
          <van-checkbox v-model="item.isChecked" @change="updateGood(item.skuId, $event)"></van-checkbox>
        </van-col>
        <!-- 商品卡片 -->
        <van-col span="20">
          <van-card
            class="goods-card"
            :num="item.skuNum"
            :price="item.cartPrice + '.00'"
            :desc="item.skuName"
            title="特价"
            :thumb="item.imgUrl"
          >
            <!-- 步进器 -->
            <template #num>
              <van-stepper
                v-model="item.skuNum"
                @plus="updataGoodsNum('plus', item.skuId)"
                @minus="updataGoodsNum('minus', item.skuId)"
                min="1"
                max="200"
                theme="round"
                integer
              />
            </template>

            <template #tags>
              <van-tag plain type="default">白色</van-tag>
            </template>
          </van-card>
        </van-col>
      </van-row>

      <!-- 左滑删除 -->
      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" @click="DelCart(item.skuId)" />
      </template>
    </van-swipe-cell>

    <!-- 空状态 -->
    <van-empty v-else :description="emptyDes">
      <router-link v-if="!userInfo.token" to="login">
        <van-button round type="danger" class="bottom-button"> 登录 </van-button>
      </router-link>

      <router-link v-else to="/home" open-type="switchTab">
        <van-button round type="danger" class="bottom-button"> 去购物~ </van-button>
      </router-link>
    </van-empty>

    <van-submit-bar :price="priceTotal" button-text="结算" @submit="onSubmit" decimal-length="2">
      <van-checkbox :checked="statusAll" v-model="isAllSelect" @change="onAllSelect($event)">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script lang="ts" setup>
import { reqCartList, reqCartAllSelect, reqAddcart, reqCartstatus, reqDelCart } from '@/api/cart'
import { IReqCartListItem } from '@/types/cart'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/userInfo'
import { showFailToast } from 'vant'
import 'vant/es/toast/style'

// 仓库用户信息
const userInfo = useUserStore()
const router = useRouter()

// 导航栏模块
const onClickLeft = () => history.back()

// 商品列表模块
const cartList = ref<IReqCartListItem[]>([])
// 空状态
const emptyDes = ref('')
const isAllSelect = ref(false)

// 获取列表数据
const getCartList = async () => {
  const token = localStorage.getItem('token')
  // 判断用户是否登录
  if (!token) {
    cartList.value = []
    emptyDes.value = '您尚未登录，点击登录获取更多权益'
  } else {
    // 调用接口，获取购物车列表数据
    const res = await reqCartList()
    // console.log(res)

    if (res.code === 200) {
      if (res.data.length) {
        cartList.value = res.data[0].cartInfoList
      } else {
        emptyDes.value = cartList.value.length > 0 ? '' : '还没有添加商品，快去添加吧~'
      }
    }
  }
}

onMounted(() => {
  getCartList()
})

//#region 商品列表
// 改变数量
const updataGoodsNum = async (type: string, id: number) => {
  console.log(type)
  if (type === 'plus') {
    await reqAddcart(id, '1')
  } else {
    await reqAddcart(id, '-1')
  }
}
// 删除购物车单个商品
const DelCart = async (skuId: number) => {
  const res = await reqDelCart(skuId)
  if (res.code === 200) {
    console.log(res)
    cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
  }
}

// // 是否是全选功能
const updateGood = async (id: number, event: boolean) => {
  const isChecked = event ? 1 : 0
  const res = await reqCartstatus(id, isChecked)
  console.log(res)
  // if (res.code !=== 200) {
  // cartList.value.forEach((item) => {
  //   if (item.skuId === id) {
  //     item.isChecked = isChecked
  //   }
  // })
  // getCartList()
  // return
  // }
}

// 全选和不全选
const onAllSelect = async (event: any) => {
  console.log(event)
  // 准备最新的状态
  const isChecked = event === true ? 1 : 0
  // 准备 skuIdList 数组
  const skuIdList = ref<number[]>([])
  cartList.value.forEach((item) => {
    skuIdList.value.push(item.skuId)
  })
  // 传递参数，发送请求
  const res = await reqCartAllSelect(isChecked, skuIdList.value as [])

  if (res.code === 200) {
    // 请求成功以后，更新本地的数据
    cartList.value.forEach((item) => {
      item.isChecked = isChecked
    })
  }
}

// 判断是否全被选中
const statusAll = computed(() => {
  let isChecked = false
  if (cartList.value.length) {
    isChecked = cartList.value.every((item) => item.isChecked)
  }
  return isChecked
})

const checkedOne = computed(() => {
  return cartList.value.some((item) => item.isChecked)
})
//#endregion

//#region 结算模块
// 结算

const priceTotal = computed(() => {
  let allPrice = 0
  cartList.value.forEach((item) => {
    if (item.isChecked) {
      allPrice += item.cartPrice * item.skuNum * 100
    }
  })
  return allPrice
})

const onSubmit = () => {
  if (!checkedOne.value) {
    console.log(checkedOne)
    showFailToast('请选择要购买的商品')
    return
  }
  router.push('/pay')
}

//#endregion
</script>

<script lang="ts">
export default {
  name: 'VCart'
}
</script>

<style lang="scss" scoped>
.container {
  height: 700px;
  background-color: #f4f4f4;
}

.swiper {
  width: 375px;
  height: 150px;
  background-color: #ffffff;
  border-radius: 20px;
  margin-top: 5px;
  div {
    font-size: 16px;
    display: flex;
    span {
      font-size: 10px;
      font-weight: 400;
      &:first-child {
        font-size: 18px;
        font-weight: 700;
      }
    }
  }
}
.van-submit-bar {
  position: fixed;
  left: 0;
  bottom: 50px !important;
}

.bottom-button {
  width: 160px;
  height: 40px;
}

// 商品列表
.van-swipe-cell {
  border-radius: 20px;
}
.goods-card {
  margin: 0;
  background-color: #ffffff;
  margin-top: 10px;
}

.delete-button {
  height: 100%;
}
</style>
